
#include "StdAfx.h"
#include "IniFile.h"
#include "Tokenizer.h"

IniFile::IniFile(){ 	
}

IniFile::~IniFile(){
}

int IniFile::read_numeric( char* file_name, char* section, char* key, int default_value ){
	if(! open( file_name, "r" ) )
		return default_value;
	
	if(! find_section( section ) )
		return default_value;
	
	char ret[ DEF_BUFFER ];
	memset( ret, 0, sizeof( char ) * DEF_BUFFER );

	if(! find_key( key, ret ) )
		return default_value;

	close();

	return atoi( ret );
}

int IniFile::read_string( char* file_name, char* section, char* key, char* ret, int in_size ){
	if( in_size >= DEF_BUFFER )
		return DEFAULT_FAIL;

	memset( ret, 0, sizeof( char ) * in_size );

	if(! open( file_name, "r" ) )
		return DEFAULT_FAIL;
	
	if(! find_section( section ) )
		return DEFAULT_FAIL;

	if(! find_key( key, ret ) )
		return DEFAULT_FAIL;

	close();	

	return DEFAULT_SUCCESS;
}

bool IniFile::find_section( char* section ){
	Tokenizer tok;
	char tmp[ DEF_BUFFER ];
	memset( tmp, 0, sizeof( char ) * DEF_BUFFER );

	while( getLine( tmp, DEF_BUFFER ) ){
		if(! tok.getToken( tmp, section, '[', ']' ) )
			continue;

		return true;
	}

	return false;
}

bool IniFile::find_key( char* key, char* ret ){
	Tokenizer tok;
	char tmp[ DEF_BUFFER ];
	memset( tmp, 0, sizeof( char ) * DEF_BUFFER );	

	while( getLine( tmp, DEF_BUFFER ) ){
		if( tmp[ 0 ] == '[' )
			return false;

		if(! tok.getSpaceValue( tmp, ret, DEF_BUFFER, key, "=" ) )
			continue;

		return true;
	}

	return false;
}
